 package com.food.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import com.food.dao.service.MemberService;
import com.food.dao.service.RecipeService;
import com.food.model.Member;
import com.food.model.Recipe;

/**
 * Servlet implementation class Register
 */
@WebServlet("/member/UpdateMb")
public class UpdateMb extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			processMultipart(request, response);
		} else {
			//errorMsgs.put("errMultipart" , "���O Multipart ���");
			//RequestDispatcher rd = request
			//		.getRequestDispatcher("InsertRecord/insertBLOBError.jsp");
			//rd.forward(request, response);
			//return;
		}

	}

	private void processMultipart(HttpServletRequest req,
			HttpServletResponse res) throws ServletException, IOException {
		
		Map<String, String> errorMsgs = new HashMap<String, String>();
		req.setCharacterEncoding("UTF-8");
		HttpSession session = req.getSession();
		req.setAttribute("ErrMsg", errorMsgs);
		session.setAttribute("ErrMsg", errorMsgs);
		try {
			String  mbaccount = ""; 
			String  mbpasswordStr = "";
			byte[] mbpassword=null;
			String  mbname = "";
			String  mbsex = "";
			String  mbidentity = "";
			String  mbbirthStr = "";
			java.sql.Date mbbirth= null;
			String mbnick = "";
			String  mbemail = "";
			String  mbtel = "";
			String  mbaddr = "";
			String mbidStr = "";
			int mbid = 0;
			String pathName = "";
			int sizeInBytes = 0 ;
			InputStream is = null ; 
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(req);
			Iterator<FileItem> itor = items.iterator();
			while (itor.hasNext()) {
				FileItem fitem =  itor.next();
				if (fitem.isFormField()) {
					String fldName = fitem.getFieldName();
					if (fldName.equals("mbaccount")){
						mbaccount = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						//mbaccount = fitem.getString();
		                System.out.println(mbaccount);
		                if (mbaccount == null || mbaccount.trim().length() == 0) {
		                	//System.out.println("BookInsertServlet.java, title Error");
		                	errorMsgs.put("errMbpassword" , "請輸入帳號");
		                } else {
		                	req.setAttribute("mbaccount", mbaccount);
		                }
					} else if (fldName.equals("mbpassword")){
						//mbpassword = fitem.get
		
						System.out.println(mbpassword);
						if (mbpasswordStr == null || mbpasswordStr.trim().length() == 0) {
		                	errorMsgs.put("errMbpassword" , "請輸入密碼");
						} else {
							
							System.out.println(mbpassword);
		                	req.setAttribute("mbpassword", mbpasswordStr);
		                }
					} else if (fldName.equals("mbname")){
						mbname = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbname);
						if (mbname == null || mbname.trim().length() == 0) {
		                	errorMsgs.put("errMbname" , "請輸入姓名");
		                } else {
		                	req.setAttribute("mbname", mbname);
		                }						
						
					} else if (fldName.equals("mbsex")){
						mbsex = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbsex);    
						req.setAttribute("mbsex", mbsex);
			                
					}else if (fldName.equals("mbidentity")){
						mbidentity = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbidentity);
						req.setAttribute("mbidentity", mbidentity);
		                
					}  else if (fldName.equals("mbbirth")){
						mbbirthStr = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						long time = sFormat.parse(mbbirthStr).getTime();
						mbbirth = new java.sql.Date(time);
						System.out.println(mbbirth);
						req.setAttribute("mbbirth", mbbirthStr);
					} else if (fldName.equals("mbnick")){
						mbnick = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbnick);
						req.setAttribute("mbnick", mbnick);
	                
					}
					else if (fldName.equals("mbemail")){
						mbemail = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbemail);
						req.setAttribute("mbemail", mbemail);
	                
					}
					else if (fldName.equals("mbtel")){
						mbtel = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbtel);
						req.setAttribute("mbtel", mbtel);
	                
					}
					else if (fldName.equals("mbaddr")){
						mbaddr = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						System.out.println(mbaddr);
						req.setAttribute("mbaddr", mbaddr);
	                
					}
					else if (fldName.equals("mbid")){
						mbidStr = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						mbid = Integer.parseInt(mbidStr);
						System.out.println(mbaddr);
						req.setAttribute("mbaddr", mbaddr);
	                
					}
				}
				else{
		//		else if (fldName.equals("rimg")){
					System.out.println("123456789aaaaaaaaaa");
					String fieldName = fitem.getFieldName();
					pathName = fitem.getName();  // �����Ϥ��ɪ��ɦW
					if (pathName != null && pathName.trim().length() > 0) {
						System.out.println("123456789");
						String contentType = fitem.getContentType();  
						sizeInBytes = (int)fitem.getSize();   
						is = fitem.getInputStream();
					} else {
						errorMsgs.put("errPicture" , "請加入圖片");
					}
				}
			}
			
//			if (!errorMsgs.isEmpty()) {
//			   RequestDispatcher rd = req.getRequestDispatcher("/top/top.jsp");
//			   rd.forward(req, res);
//			   return;
//			} 
			
			Member m = new Member();
			m.setMbid(mbid);
			m.setMbaccount(mbaccount);
			m.setMbpassword(mbpassword);
			m.setMbname(mbname);
			m.setMbsex(mbsex);
			m.setMbidentity(mbidentity);
			m.setMbbirth(mbbirth);
			m.setMbnick(mbnick);
			m.setMbemail(mbemail);
			m.setMbtel(mbtel);
			m.setMbaddr(mbaddr);
			System.out.println(m);
			
			MemberService  service = new MemberService();
			service.updateMember(m, is, sizeInBytes);
			System.out.println("up");
			errorMsgs.put("success" , "新增成功");
			String path = req.getContextPath();
			res.sendRedirect(res.encodeRedirectURL(path+"/index.jsp"));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			errorMsgs.put("Exception", e.getMessage());
			RequestDispatcher rd = req.getRequestDispatcher("/member/Registered.jsp");
			rd.forward(req, res);
		}
	

	}

}
